package com.kanshu.client.ui.activity.ipc;

import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.RemoteException;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;

import com.kanshu.basictest.BookManager;
import com.kanshu.basictest.IBookShelfChangedListener;
import com.kanshu.basictest.model.ipc.Book;
import com.kanshu.client.R;
import com.kanshu.client.model.menu.MenuItem;
import com.kanshu.client.ui.base.BaseMenuActivity;

import java.util.ArrayList;
import java.util.List;

import static com.kanshu.client.constants.PubContants.MSG_NEW_BOOK_ADDED;

public class AIDLTestActivity extends BaseMenuActivity implements Handler.Callback {

    private static final String TAG = "AIDLTestActivity";

    private BookManager mBookManager;

    //处理新书通知的Handler
    private final Handler mNewBookHandler = new Handler(this);

    @Override
    protected String provideBarTitle() {
        return "AIDL测试";
    }

    @Override
    protected List<? extends MenuItem> provideMenuData() {
        List<MenuItem> menuItems = new ArrayList<>();
        menuItems.add(0, new MenuItem("读取Book列表", R.color.blue_200));
        menuItems.add(1, new MenuItem("订阅新书通知", R.color.blue_200));
        menuItems.add(2, new MenuItem("取消订阅新书通知", R.color.blue_200));
        return menuItems;
    }


    @Override
    protected void init() {
        super.init();
        bindServer();
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        switch (position) {
            case 0://读取Book列表
                getBookList();
                break;
            case 1://订阅新书通知
                registerNewBookNotice();
                break;
            case 2://取消订阅新书通知
                unRegisterNewBookNotice();
                break;
            default:// do nothing
                break;

        }

    }

    //服务连接
    private ServiceConnection conn = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            //运行在客户端的主线程上，因此这里不能处理好事操作
            Log.i(TAG, "onServiceConnected: 当前线程：" + Thread.currentThread().getName());
            mBookManager = BookManager.Stub.asInterface(service);
            //为Binder设置死亡代理，一旦Binder死亡，将会调用DeathRecipient#
            try {
                service.linkToDeath(deathRecipient, 0);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            //运行在客户端的主线程上
            Log.i(TAG, "onServiceDisconnected: 当前线程：" + Thread.currentThread().getName());
            mBookManager = null;
        }
    };

    //Binder的死亡代理
    private IBinder.DeathRecipient deathRecipient = new IBinder.DeathRecipient() {
        @Override
        public void binderDied() {
            if (mBookManager == null) {
                return;
            }

            mBookManager.asBinder().unlinkToDeath(deathRecipient, 0);
            mBookManager = null;
            //当原binder死亡时，这里重新进行绑定服务
            bindServer();

        }
    };

    private IBookShelfChangedListener.Stub mListener = new IBookShelfChangedListener.Stub() {
        @Override
        public void onNewBookAdded(Book newBook) throws RemoteException {
            //运行在客户端的Binder线程池中的某条线程上，因此这里不能只从UI操作
            Log.i(TAG, "onNewBookAdded: 当前线程：" + Thread.currentThread().getName());
            mNewBookHandler.obtainMessage(MSG_NEW_BOOK_ADDED, newBook).sendToTarget();

        }
    };

    @Override
    public boolean handleMessage(Message msg) {
        switch (msg.what) {
            case MSG_NEW_BOOK_ADDED:
                //主线程中处理消息
                Log.i(TAG, "MSG_NEW_BOOK_ADDED: 当前线程：" + Thread.currentThread().getName());
                Log.i(TAG, "handleMessage: 新书到了：" + msg.obj);
                break;
            default:
                break;
        }


        return true;
    }


    private void bindServer() {
        Intent intent = new Intent();
        intent.setComponent(new ComponentName("com.kanshu.basictest", "com.kanshu.basictest.service.BookManagerService"));
        bindService(intent, conn, Service.BIND_AUTO_CREATE);
    }

    //读取Book列表
    private void getBookList() {
        if (mBookManager != null) {
            try {
                List<Book> books = mBookManager.getBookList();
                showPromptDialog("图书列表", books.toString());
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        } else {
            showToastShort("尚未绑定服务端！");
        }
    }

    //订阅新书通知
    private void registerNewBookNotice() {
        if (mBookManager != null) {
            try {
                mBookManager.registerListener(mListener);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        } else {
            showToastShort("尚未绑定服务端！");
        }
    }

    //取消订阅新书通知
    private void unRegisterNewBookNotice() {
        if (mBookManager != null) {
            try {
                mBookManager.unRegisterListener(mListener);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        } else {
            showToastShort("尚未绑定服务端！");
        }
    }


    @Override
    protected void onDestroy() {
        //如果还连接的远程服务，注销监听
        if (mBookManager != null && mBookManager.asBinder().isBinderAlive()) {
            try {
                mBookManager.unRegisterListener(mListener);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
        unbindService(conn);
        super.onDestroy();

    }
}
